package com.chen.integral.module.test.service.impl;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.core.FileURIResolver;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;

/*
word转html
poi-scratchpad
poi-ooxml
3.12 版本在docx和doc word转html的时候不会报错
*/

/**
 * @Title: manager-spring-mvc-hb
 * @Description: to do
 * @Author: chenjiwei
 * @Date: 2020-11-19 2:06
 * @Version: 1.0.0
 */
public class WordToHtml {
    // https://blog.csdn.net/somehow1002/article/details/104685854
    public void docxToHtml() throws IOException {
        String htmlPath  = "d:/3.html";
        String imagepath = "F:\\apps-other\\db\\";
//        String fileName = "D:\\Git\\experience\\java基础.docx";
        String docPath = "F:\\apps-other\\db\\template.docx";
        File f = new File(docPath);
        if (!f.exists()) {
            System.out.println("不存在文件！");
        } else {
            if (f.getName().endsWith(".docx") || f.getName().endsWith(".DOCX")) {

                // 1) 加载word文档生成 XWPFDocument对象
                InputStream in = new FileInputStream(f);
                XWPFDocument document = new XWPFDocument(in);

                // 2) 解析 XHTML配置 (这里设置IURIResolver来设置图片存放的目录)
                File imageFolderFile = new File(imagepath);
                if(!imageFolderFile.exists()){//图片目录不存在则创建
                    imageFolderFile.mkdirs();
                }
                XHTMLOptions options = XHTMLOptions.create().URIResolver(new FileURIResolver(imageFolderFile));
                options.setExtractor(new FileImageExtractor(imageFolderFile));
                options.setIgnoreStylesIfUnused(false);
                options.setFragment(true);

                // 3) 将 XWPFDocument转换成XHTML
                OutputStream out = new FileOutputStream(new File(htmlPath));
                XHTMLConverter.getInstance().convert(document, out, options);

                //                也可以使用字符数组流获取解析的内容
                //                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                //                XHTMLConverter.getInstance().convert(document, baos, options);
                //                String content = baos.toString();
                //                System.out.println(content);
                //                baos.close();
            } else {
                System.out.println("仅支持word2007以上版本");
            }
        }
    }

    /*
    调用的时候word是doc
    如果报错如下
    The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents.
    You need to call a different part of POI to process this data (eg XSSF instead of HSSF)
    这是版本问题。
    解决办法：可以将.docx文件另存为.doc文件再进行处理（不是直接改扩展名）。
    当然也可以使用XSSF 来接收处理文件
    */
    public void docToHtml() throws IOException, TransformerException, ParserConfigurationException {
         String docPath  = "d:/2.doc";
         String htmlPath  = "d:/3.html";
         final String imagepath = "d:/test/image/";
         final String docFile = docPath;
         InputStream input = new FileInputStream(new File(docFile));
         HWPFDocument wordDocument = new HWPFDocument(input);
         WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
         //设置图片存放的位置
         wordToHtmlConverter.setPicturesManager(new PicturesManager() {
             public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {
                 File imgPath = new File(imagepath);
                 if(!imgPath.exists()){//图片目录不存在则创建
                     imgPath.mkdirs();
                 }
                 File file = new File(imagepath + suggestedName);
                 try {
                     OutputStream os = new FileOutputStream(file);
                     os.write(content);
                     os.close();
                 } catch (FileNotFoundException e) {
                     e.printStackTrace();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
                 return imagepath + suggestedName;
             }
         });

         //解析word文档
         wordToHtmlConverter.processDocument(wordDocument);
         Document htmlDocument = wordToHtmlConverter.getDocument();

         File htmlFile = new File(htmlPath);
         OutputStream outStream = new FileOutputStream(htmlFile);

         //也可以使用字符数组流获取解析的内容
 //        ByteArrayOutputStream baos = new ByteArrayOutputStream();
 //        OutputStream outStream = new BufferedOutputStream(baos);
         DOMSource domSource = new DOMSource(htmlDocument);
         StreamResult streamResult = new StreamResult(outStream);

         TransformerFactory factory = TransformerFactory.newInstance();
         Transformer serializer = factory.newTransformer();
         serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
         serializer.setOutputProperty(OutputKeys.INDENT, "yes");
         serializer.setOutputProperty(OutputKeys.METHOD, "html");

         serializer.transform(domSource, streamResult);

         //也可以使用字符数组流获取解析的内容
 //        String content = baos.toString();
 //        System.out.println(content);
 //        baos.close();
         outStream.close();
    }
    public static void main(String[] args) throws IOException, TransformerException, ParserConfigurationException {
        new WordToHtml().docToHtml();
        System.out.println("hello word!");
    }
}
